package com.personal.system.service.dataScope;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.personal.model.system.SysDept;
import com.personal.system.entity.sys.SysRoleDept;
import com.personal.system.hal.DataBaseHelper;
import com.personal.system.mapper.sys.SysDeptMapper;
import com.personal.system.mapper.sys.SysRoleDeptMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 数据权限解析 {@link com.personal.system.ann.DataScopeType} 2,4时调用
 */
@Service("dss")
public class SysDataScopeService {

    @Resource
    private SysRoleDeptMapper roleDeptMapper;
    @Resource
    private SysDeptMapper deptMapper;

    // 根据角色查部门
    public String getRoleCustom(Long roleId) {
        List<SysRoleDept> list = roleDeptMapper.selectList(
                new LambdaQueryWrapper<SysRoleDept>()
                        .select(SysRoleDept::getDeptId)
                        .eq(SysRoleDept::getRoleId, roleId));
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(rd -> Convert.toStr(rd.getDeptId())).filter(Objects::nonNull).collect(Collectors.joining(","));
        }
        return null;
    }
    // 查本部门及以下部门
    public String getDeptAndChild(Long deptId) {
        List<SysDept> deptList = deptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .select(SysDept::getId)
                .apply(DataBaseHelper.findInSet(deptId, "tree_path")));
        List<Long> ids = deptList.stream()
                .map(e -> Convert.toLong(e.getId()))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        ids.add(deptId);
        List<SysDept> list = deptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .select(SysDept::getId).in(SysDept::getId, ids));
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map( d -> Convert.toStr(d.getId())).filter(Objects::nonNull).collect(Collectors.joining(","));
        }
        return null;
    }

}
